/*
 * @Descripttion: 
 * @version: 
 * @Author: yuanliutech
 * @Date: 2022-11-01 14:23:34
 * @LastEditors: yuanliutech@lwj
 * @LastEditTime: 2023-02-15 10:34:34
 */
const app = getApp()
import Dialog from '@vant/weapp/dialog/dialog';
import {
    showMsg
} from '../../../../utils/config.js'

import {
    validateEmoji,
    validateSpecial
} from '../../../../utils/validate.js'
import {
    reqisolationPersonEdit,
    reqDeviceBySpaceId,
    reqDeviceByImei,
    reqDeviceUnBind,
    reqDeviceAdd,
    reqRegion,
    reqRegionLevel,
} from '../../../../request/api'
let arr = []
for (let i = 2; i < 30; i++) {
    arr.push(i)
}
Page({
    data: {
        navHeight: app.globalData.navHeight + 'px', //头部距离
        bottomHeight: app.globalData.bottomHeight + 'px', //iphone底部距离
        currentTab: 0,
        tabList: [{
            id: 0,
            name: '隔离人'
        }, {
            id: 1,
            name: '设备'
        }, ],
        form: {
            id: '',
            spaceId: '',
            type: '',
            isolationType: '',
            fromCityName: '',
            startTime: '',
            days: '',
            name: '',
            gender: '',
            mobile: '',
            idCard: '',
        },
        // 隔离因素开始
        showIsolationType: false,
        isolationTypeList: [{
            id: 1,
            text: '密接',
        }, {
            id: 2,
            text: '次密接',
        }, {
            id: 3,
            text: '确诊',
        }, ],
        // 隔离因素结束
        // 隔离方式开始
        showIsolationMode: false,
        isolationModeList: [{
            id: 1,
            text: '居家隔离',
        }, {
            id: 2,
            text: '酒店隔离',
        }, {
            id: 3,
            text: '定点医院隔离',
        }, {
            id: 4,
            text: '其他隔离'
        }, ],
        // 隔离方式结束

        // 来源地区选择开始
        showRegion: false,
        tabList1: [{
            id: 0,
            name: '省',
        }, {
            id: 1,
            name: '市',
        }, {
            id: 2,
            name: '区',
        }, ],
        currentTab1: 0,
        provinceList: [],
        provinceCode: '',
        provinceName: '',
        cityList: [],
        cityCode: '',
        cityName: '',
        areaList: [],
        areaCode: '',
        areaName: '',
        // 来源地区选择结束

        // 隔离开始时间开始  
        showStartTime: false,
        timePickerConfig: {
            isTabbar: false, //是否为tabbar页面
            endDate: false, // 是否需要结束时间，为true时显示开始时间和结束时间两个picker
            column: "minute", //可选的最小时间范围day、hour、minute、secend
            dateLimit: true,
            initStartTime: '',
            initEndTime: '',
            limitStartTime: "2015-01-01 00:00:00", //最小可选时间--必填
            limitEndTime: "2100-05-06 23:59:59" //最大可选时间--必填
        },
        // 隔离开始时间结束
        // 隔离天数开始
        showIsolationDay: false,
        isolationDayList: [1, ...arr, 30],
        // 隔离天数结束
        // 设备开始
        imeiList: [],
        // 设备结束
        // 隔离人开始
        showIsolationGender: false,
        isolationGenderList: [{
                id: 0,
                text: "女"
            },
            {
                id: 1,
                text: '男'
            }
        ],
        // 隔离人结束
    },
    onLoad(e) {
        this.getItemInfo(e)
    },
    onShow() {
        this.getRegion()
    },

    onReady() {
        let pickerType = this.selectComponent('.picker-type') //隔离因素
        let pickerMode = this.selectComponent('.picker-mode') //隔离方式
        let pickerDays = this.selectComponent('.picker-days') //隔离天数
        let pickerGender = this.selectComponent('.picker-gender') //性别
        pickerType.setIndexes([this.data.form.type - 1])
        pickerMode.setIndexes([this.data.form.isolationType - 1])
        pickerDays.setIndexes([this.data.form.days - 1])
        pickerGender.setIndexes([this.data.form.gender])
    },
    // 获取信息
    getItemInfo(e) {
        let item = JSON.parse(e.info)
        this.setData({
            'form.spaceId': item.spaceId,
            'form.spaceName': item.spaceName,
            'form.id': item.id,
            'form.type': item.type,
            'form.isolationType': item.isolationType,
            'form.fromCityName': item.fromCityName ? item.fromCityName : '',
            'form.startTime': item.startTime,
            'timePickerConfig.initStartTime': item.startTime,
            'form.days': item.days,
            'form.name': item.name,
            'form.gender': item.gender,
            'form.mobile': item.mobile,
            'form.idCard': item.idCard,
        })
        this.getAlarmReceiverBySpaceId(item.spaceId)
    },
    //  点击切换
    swichNav(e) {
        let {
            current
        } = e.currentTarget.dataset
        this.setData({
            currentTab: current
        })
    },
    // 滑动切换
    bindChangeTab(e) {
        let {
            current
        } = e.detail
        this.setData({
            currentTab: current
        })
    },

    /* --------------------------------隔离点开始-------------------------- */
    // 弹出隔离因素
    clickIsolationType() {
        this.setData({
            showIsolationType: true
        })
    },
    // 隐藏隔离因素
    isolationTypeClose() {
        this.setData({
            showIsolationType: false
        })
    },
    // 确定隔离因素
    isolationTypeConfirm(e) {
        const {
            value,
        } = e.detail;
        this.setData({
            "form.type": value.id,
            showIsolationType: false,
        })
    },
    // 弹出隔离方式
    clickIsolationMode() {
        this.setData({
            showIsolationMode: true
        })
    },
    // 隐藏隔离方式
    isolationModeClose() {
        this.setData({
            showIsolationMode: false
        })
    },
    // 确定隔离方式
    isolationModeConfirm(e) {
        const {
            value,
        } = e.detail;
        this.setData({
            "form.isolationType": value.id,
            showIsolationMode: false,
        })
    },
    // 来源地区开始
    swichTab1(e) {
        let {
            id
        } = e.currentTarget.dataset
        this.setData({
            currentTab1: id
        })
    },

    bindChangeTab1(e) {
        let {
            current
        } = e.detail
        this.setData({
            currentTab1: current
        })
    },
    // 弹出省市区
    showRegionClick() {
        this.setData({
            showRegion: true
        })
    },
    closeRegion() {
        this.setData({
            showRegion: false
        })
    },
    // 获取省级数据
    async getRegion() {
        const res = await reqRegion()
        if (res.code !== 20000) return showMsg(res.message)
        console.log(res);
        let {
            rows
        } = res.data
        this.setData({
            provinceList: rows
        })
    },
    // 点击省
    async provinceClick(e) {
        this.setData({
            cityList: [],
            areaList: [],
            cityCode: "",
            areaCode: "",
        })
        let {
            item
        } = e.currentTarget.dataset
        const res = await reqRegionLevel(item.regionCode)
        if (res.code !== 20000) return showMsg(res.message)
        let {
            rows
        } = res.data
        this.setData({
            provinceCode: item.regionCode,
            provinceName: item.regionName,
            cityList: rows,
            currentTab1: 1,
        })
    },
    // 点击市
    async cityClick(e) {
        this.setData({
            areaList: [],
            areaCode: "",
        })
        let {
            item
        } = e.currentTarget.dataset
        const res = await reqRegionLevel(item.regionCode)
        if (res.code !== 20000) return showMsg(res.message)
        let {
            rows
        } = res.data
        this.setData({
            cityCode: item.regionCode,
            cityName: item.regionName,
            areaList: rows,
            currentTab1: 2,
        })
    },
    // 点击区
    async areaClick(e) {
        this.setData({
            streetList: [],
            streetCode: "",
        })
        let {
            item
        } = e.currentTarget.dataset
        this.setData({
            areaCode: item.regionCode,
            areaName: item.regionName,
        })
    },
    // 确定
    confirmRegion() {
        let {
            areaCode,
            provinceName,
            cityName,
            areaName,
        } = this.data
        if (!areaCode) return showMsg("请选择到区")
        this.setData({
            'form.fromCityName': provinceName + cityName + areaName
        })
        this.closeRegion()
    },
    // 来源地区结束

    // 点击开始时间
    clickShowStartTime() {
        this.setData({
            showStartTime: true,
        });
    },
    // 隐藏开始时间
    startTimeClose() {
        this.setData({
            showStartTime: false,
        });
    },
    // 确定开始时间
    startTimeChange(e) {
        this.setData({
            'form.startTime': e.detail.startTime,
            showStartTime: false,
        });
    },
    // 输入天数获取
    dayChange(e) {
        let {
            value
        } = e.detail
        this.setData({
            "form.days": value
        })
    },
    // 弹出天数弹窗
    clickIsolationDay() {
        this.setData({
            showIsolationDay: true
        })
    },
    // 隐藏天数弹窗
    isolationDayClose() {
        this.setData({
            showIsolationDay: false
        })
    },
    // 确定天数弹窗
    isolationDayConfirm(e) {
        const {
            value,
            index
        } = e.detail;
        this.setData({
            "form.days": value,
            showIsolationDay: false
        })
    },

    /* --------------------------------隔离点结束-------------------------- */


    /* --------------------------------设备开始-------------------------- */
    // 空间id获取设备
    async getAlarmReceiverBySpaceId() {
        const res = await reqDeviceBySpaceId(this.data.form.spaceId)
        let {
            rows
        } = res.data
        let arr = []
        rows.forEach((item, index) => {
            arr.push({
                id: index,
                devicePrimaryId: item.id,
                imei: item.imei,
                type: item.productName,
            })
        })
        this.setData({
            imeiList: arr
        })
    },
    // 点击新增一条设备输入框
    clickAddDevice() {
        let {
            imeiList
        } = this.data
        let count = 0
        let length = imeiList.length
        imeiList.forEach(item => {
            if (item.devicePrimaryId) {
                count++
            }
        })
        if (length - count >= 5) return showMsg("一次最多新增5台设备")
        // let id = imeiList[imeiList.length - 1].id + 1
        let id = imeiList.length === 0 ? 0 : imeiList[imeiList.length - 1].id + 1
        imeiList.push({
            id,
            imei: '',
            type: ''
        })
        this.setData({
            imeiList
        })
    },
    // 判断imei是否已存在
    async getDeviceByImei(id, imei) {
        let {
            imeiList
        } = this.data
        const res = await reqDeviceByImei(imei)
        if (res.code === 12020 || res.code === 12021) {
            imeiList.forEach(item => {
                if (item.id === id) {
                    item.imei = ''
                    item.type = ''
                }
            })
            // setTimeout(() => {
            this.setData({
                imeiList
            })
            // }, 500)
            showMsg(res.message)
            return
        }
        if (res.code !== 20000) return showMsg(res.message)
        imeiList.forEach(item => {
            if (item.id === id) {
                item.imei = imei
                item.type = res.data.row.productName
            }
        })
        this.setData({
            imeiList
        })
    },
    // 获取设备imei
    imeiChange(e) {
        let {
            id
        } = e.target.dataset
        let {
            value
        } = e.detail
        if (value.length >= 15) {
            this.getDeviceByImei(id, value)
        }
        if (value.length <= 0) {
            // 删除到没有时，清除imei和类型
            let {
                imeiList
            } = this.data
            imeiList.forEach(item => {
                if (item.id === id) {
                    item.imei = ''
                    item.type = ''
                }
            })
            this.setData({
                imeiList
            })
        }
    },
      // js判断字符串是否为JSON格式
  isjson(str) {
    if (typeof str == 'string') {
        try {
            var obj = JSON.parse(str);
            if (typeof obj == 'object' && obj) {
                return true;
            } else {
                return false;
            }

        } catch (e) {
            console.log('error：' + str + '!!!' + e);
            return false;
        }
    }
    console.log('It is not a string!')
},
    /**
     * @name:  扫码imei
     * @msg: 掉接口时记得询问清楚截取方法
     * @return {*}
     */
    imeiScan(e) {
        let that = this
        let {
            id
        } = e.target.dataset
        let qrcode = ''
        wx.scanCode({
            success(res) {
                qrcode = res.result;
                if (!qrcode) return showMsg('扫描失败，请重新扫描')
                if (qrcode.length >= 3) {
                    if (that.isjson(qrcode)) {
                        const result = JSON.parse(qrcode);
                            // JSON字符格式
                            that.setData({
                                searchValue: result.ID, //威视达康摄像机取值，后续看需求更改 lc
                            })
                            that.getDeviceByImei(id, result.ID)
                        } else {
                            // 非JSON格式
                            that.setData({
                                searchValue: qrcode,
                            })
                            that.getDeviceByImei(id, qrcode)
                        }
                } else {
                    showMsg('扫描失败，请重新扫描')
                    return
                }
            }
        })
    },
    // 扫码后赋值imei
    imeiScanChange(id, code) {
        let {
            imeiList
        } = this.data
        imeiList.forEach(item => {
            if (item.id === id) {
                item.imei = code
            }
        })
        this.setData({
            imeiList
        })
    },
    // 清除imei
    imeiClear(e) {
        let {
            info
        } = e.target.dataset
        let {
            imeiList
        } = this.data
        imeiList.forEach((item, index) => {
            if (item.id === info.id) {
                if (info.devicePrimaryId) {
                    this.getDeviceUnBind(info.devicePrimaryId, index)
                } else {
                    item.imei = ''
                    item.type = ''
                }
            }
        })
        this.setData({
            imeiList
        })
    },

    getDeviceUnBind(id, index) {
        let {
            imeiList
        } = this.data
        Dialog.confirm({
                title: '温馨提示',
                message: '此操作将解绑该设备，是否继续？',
            })
            .then(async () => {
                const res = await reqDeviceUnBind({
                    id
                })
                if (res.code != 20000) return showMsg(res.message);

                imeiList.splice(index, 1)
                imeiList.forEach((item, index) => {
                    item.id = index
                })
                this.setData({
                    imeiList
                })
                showMsg("解绑成功")
            })
            .catch(() => {});
    },


    /* --------------------------------设备结束-------------------------- */


    /* --------------------------------隔离人开始-------------------------- */
    // 获取隔离人姓名
    isolationNameChange(e) {
        this.data.form.name = validateEmoji(e.detail.value.replace(/\s+/g, ''))
        this.setData({
            "form.name": this.data.form.name
        })
    },
    // 清除隔离人姓名
    clearName() {
        this.setData({
            "form.name": ''
        })
    },
    /**
     * @name: 获取性别
     * @msg: 1、弹出弹窗   2、隐藏弹窗  3、确定值
     * @return {*}
     */
    // 弹出弹窗
    clickIsolationGender() {
        this.setData({
            showIsolationGender: true,
        })
    },
    // 隐藏弹窗
    isolationGenderClose() {
        this.setData({
            showIsolationGender: false
        })
    },
    // 确定值
    isolationGenderConfirm(e) {
        const {
            value,
        } = e.detail;
        this.setData({
            "form.gender": value.id,
            showIsolationGender: false,
        })
    },

    // 获取隔离人电话
    isolationMobileChange(e) {
        let {
            value
        } = e.detail
        this.setData({
            "form.mobile": value
        })
    },
    // 清除隔离人电话
    clearMobile() {
        this.setData({
            "form.mobile": ''
        })
    },

    // 获取证件号
    isolationIdCardChange(e) {
        let {
            value
        } = e.detail
        this.setData({
            "form.idCard": value
        })
    },
    // 清除证件号
    clearIdCard() {
        this.setData({
            "form.idCard": ''
        })
    },

    /* --------------------------------隔离人结束-------------------------- */
    // 确认新增隔离人员,
    confirm() {
        if (this.data.disabledBtn) return
        let {
            form,
        } = this.data
        if (!form.name) return showMsg("请输入隔离人姓名")
        if (form.name.length < 2) return showMsg("隔离人姓名的长度不能少于2位")
        if (form.gender === '' || form.gender === null || form.gender === undefined) return showMsg("请选择隔离人性别")
        let {
            currentTab
        } = this.data
        if (currentTab === 0) {
            // 隔离人
            this.reqisolationPerson()
        } else {
            // 空间设备
            this.reqReceiverSpace()
        }
    },
    // 隔离人
    reqisolationPerson() {
        let {
            form,
        } = this.data
        let params = {
            id: form.id,
            spaceId: form.spaceId,
            type: form.type,
            fromCityName: form.fromCityName,
            isolationType: form.isolationType,
            startTime: form.startTime,
            days: form.days,
            name: form.name,
            mobile: form.mobile,
            gender: form.gender,
            idCard: form.idCard
        }
        this.reqAddFun(params)
    },
    // 隔离人请求接口
    async reqAddFun(params) {
        const res = await reqisolationPersonEdit(params)
        if (res.code != 20000) return showMsg(res.message);
        showMsg("编辑成功", "success")
        this.setData({
            disabledBtn: true
        })
        setTimeout(() => {
            wx.navigateBack({
                delta: 1,
            })
        }, 2000)
    },
    // 确定修改设备
    async reqReceiverSpace() {
        let {
            imeiList,
            form
        } = this.data
        let arr = imeiList.map(item => {
            return item.imei
        })
        let list = arr.filter(Boolean)
        if (list.length <= 0) return showMsg("请输入设备编码")
        let params = {
            spaceId: form.spaceId,
            userId: app.globalData.userId,
            imeiList: list
        }
        const res = await reqDeviceAdd(params)
        if (res.code != 20000) return showMsg(res.message);
        showMsg("编辑成功", "success")
        this.setData({
            disabledBtn: true
        })
        setTimeout(() => {
            wx.navigateBack({
                delta: 1,
            })
        }, 2000)
    },
})